package com.qidian.buy.search.service.impl;

import com.qidian.buy.entity.Item;
import com.qidian.buy.search.service.SearchService;
import com.qidian.buy.util.pojo.BuyResult;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.fetch.subphase.highlight.Highlighter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author 戴着假发的程序员
 * @Company 起点编程
 * @date 2023/5/23 13:47
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public BuyResult addIndex(Long itemId) {
        // 通过远程调用查询商品信息
        BuyResult buyResult = restTemplate.getForObject("http://buy-product/buy/item/detail?id=" + itemId, BuyResult.class);
        Map map = (Map) buyResult.getObj();
        Map item = (Map) map.get("item");
        //添加索引
        IndexRequest request = new IndexRequest("item");
        // 添加数据
        // 删除不需要存储的数据
        item.remove("num");
        item.remove("barcode");
        map.remove("cid");
        item.remove("status");
        item.remove("updated");
        // 处理图片，图片值存储一张
        Object img = item.get("image");
        if(img != null && !"".equals(img)){
            item.put("image",img.toString().split(";")[0]);
        }
        request.id(item.get("id").toString());
        request.source(item);
        // 添加索引
        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return BuyResult.ok();
    }

    @Override
    public BuyResult importIndex() {
        int page = 1;
        int limit = 100;
        int maxPageNum = 1;
        for (;page <= maxPageNum;page ++) {
            // 远程调用查询数据
            BuyResult result = restTemplate.getForObject("http://buy-product/buy/item/list?page="+page+"&limit=" + limit, BuyResult.class);
            // 取出总条数
            Long total = result.getCount();
            // 计算最大页码
            maxPageNum = (int) Math.ceil(total * 1.0 / limit);
            // 取出数据
            List list = result.getData();
            // 批量导入索引库
            BulkRequest bulkRequest = new BulkRequest();
            for (Object obj : list) {
                Map map = (Map) obj;
                // 删除不需要存储的数据
                map.remove("num");
                map.remove("barcode");
                map.remove("cid");
                map.remove("status");
                map.remove("updated");
                // 处理图片，图片值存储一张
                Object img = map.get("image");
                if(img != null && !"".equals(img)){
                    map.put("image",img.toString().split(";")[0]);
                }
                // 准备索引请求对象
                IndexRequest request = new IndexRequest("item");
                request.id(map.get("id").toString());
                request.source(map);
                bulkRequest.add(request);
            }
            // 导入索引库
            try {
                BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return BuyResult.ok();
    }

    @Override
    public BuyResult search(String keyword,int page,int limit) {

        List data = new ArrayList();

        // 查询索引库
        SearchRequest request = new SearchRequest("item");
        // 设置查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder queryBuilder = new MatchQueryBuilder("title",keyword);
        searchSourceBuilder.query(queryBuilder);
        // 处理高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("title");
        searchSourceBuilder.highlighter(highlightBuilder);
        // 分页处理
        searchSourceBuilder.from((page - 1) * limit);
        searchSourceBuilder.size(limit);
        // 设置查询资源
        request.source(searchSourceBuilder);
        // 查询
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHit[] searchHits = response.getHits().getHits();
            for (SearchHit hit : searchHits){
                Map<String, Object> map = hit.getSourceAsMap();
                // 获取高亮显示的结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField title = highlightFields.get("title");
                if(title != null){
                    Text[] fragments = title.getFragments();
                    if(fragments != null && fragments.length > 0){
                        // 用高亮显示的结果替换非高亮显示的结果
                        map.put("title",fragments[0].toString());
                    }
                }
                data.add(map);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return BuyResult.ok(data);
    }
}
